#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: ystlong
# @Date:   2019-07-07 01:23:40
# @Last Modified by:   ystlong
# @Last Modified time: 2019-07-07 03:57:04

import os, sys
import sqlite3

def list_files(root_dir, file_handle):
	for root, dirs, files in os.walk(root_dir):
		# for dir_name in dirs:
		# 	print("dir: %s"%(os.path.join(root, dir_name)))
		for file_name in files:
			file_handle(os.path.join(root, file_name), file_name)

# def test_file_handle(file_path, file_name):
# 	print("file: %s"%(file_path))
# list_files(".", test_file_handle)

class DirIndexHtml(object):
	"""docstring for DirIndexHtml"""
	def __init__(self):
		super(DirIndexHtml, self).__init__()
		self.search_tpl = """
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>search list</title>
</head>
<body>
<form action="">
	<input type="text" name="name" value="{query_str}">
</form>
<hr />
<table>
	<tr><td><a href="..">parent</a></td></tr>
	<!--<tr><td><a href="file_path">file_path</a></td></tr>-->
	{rows}
</table>
</body>
</html>
		"""
	def format_search(self, results, query_str):
		# <tr><td><a href="file_path">file_path</a></td></tr>
		row_tpl = '<tr><td><a href="{file_path}">{file_path}</a></td></tr>'
		html_content = []
		for res in results:
			file_path = res[0]
			html_content.append(row_tpl.format(file_path=file_path))
		content = self.search_tpl.format(rows="".join(html_content), query_str=query_str)
		return content
		# print(content)

class DirIndex(object):
	"""docstring for DirIndex"""
	def __init__(self, prefix_uri=''):
		super(DirIndex, self).__init__()
		self.prefix_uri = prefix_uri
		self.db_file = "gen_file_index.db"
		self.conn = sqlite3.connect(self.db_file)
		self._init_database()

	def _database_execute(self, sql, args=()):
		res = self.conn.execute(sql, args)
		self.conn.commit()
		return res

	def _init_database(self):
		# res = self._database_execute("drop table if exists files")
		res = self._database_execute("""
			create table if not exists files(
			file_path text PRIMARY KEY not null,
			file_name text not null,
			size int)
		 """)

	def _insert_one_item(self, file_path, file_name, size, date_str='', insert_count=0, insert=True):
		if insert:
			sql = """insert or replace into files (file_path, file_name, size) values(?,?,?)"""
			args = (file_path, file_name, size)
			res = self.conn.execute(sql, args)
		if insert_count / 10000 == 0:
			self.conn.commit()

	def generate_database(self):
		insert_count = 0
		def _insert_file_handle(file_path, file_name):
			nonlocal insert_count
			insert_count += 1
			print("insert file: ", file_path)
			self._insert_one_item(file_path, file_name, 0, insert_count=insert_count)
		list_files(self.prefix_uri, _insert_file_handle)
		# commit last item
		self._insert_one_item(None, None, 0, insert_count=0, insert=False)

	def search_file(self, query_str):
		sql = """select file_path, file_name from files where file_path like ?"""
		q = "%%%s%%"%("%".join(list(query_str)))
		# print(q)
		res = self._database_execute(sql, (q,)).fetchall()
		# print(res)
		return res

def cgi():
	# CGI处理模块
	import cgi, cgitb 
	# 创建 FieldStorage 的实例化
	form = cgi.FieldStorage() 
	# 获取数据
	query_name = form.getvalue('name')
	print("Content-type:text/html\n\n\n")
	di = DirIndex(".")
	res = di.search_file(query_name)
	dih = DirIndexHtml()
	print(dih.format_search(res), query_name)


def scan(root_dir):
	di = DirIndex(root_dir)
	di.generate_database()
	
def query(query_str):
	di = DirIndex(".")
	res = di.search_file(query_str)
	for r in res:
		print(r[0])

def flask_web():
	import flask
	app = flask.Flask(__name__)
	@app.route('/')
	def search():
		query_name = flask.request.args.get("name", "")
		query_name = flask.request.form.get("name", query_name)
		if query_name == None:
			query_name = ""

		di = DirIndex(".")
		res = di.search_file(query_name)
		dih = DirIndexHtml()
		res = dih.format_search(res, query_name)
		return res
	# print(sys.argv)
	if len(sys.argv) == 3:
		addr, port = sys.argv[2].split(":")
		# print(addr, port)
		app.run(host=addr, port=int(port))
	else:
		app.run()

def help():
	usage_str = """
	usage: 
		{boot_name} flask [addr:port]
		{boot_name} scan scan_relative_root_path
		{boot_name} query query_str
	""".format(boot_name=sys.argv[0])
	print(usage_str)

if __name__ == '__main__':
	try:
		if sys.argv[1] == "flask":
			flask_web()
		elif sys.argv[1] == "scan":
			scan(sys.argv[2])
		elif sys.argv[1] == "query":
			query(sys.argv[2])
	except IndexError:
		help()
		raise
	except:
		raise
	
